<?php
/*
  Template Name: add_new_product
 */
// grabs the user info and puts into vars
global $current_user, $app_abbr;
?>
<script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/bootstrap/js/bootstrap.js"></script>
    <script type="text/javascript" src="<?php echo get_template_directory_uri(); ?>/includes/js/bootbox.js"></script>
    <script type="text/javascript" src="<?php echo get_template_directory_uri() . '/includes/js/Utils.js'; ?>"></script>
    <link rel="stylesheet" type="text/css" href="<?php echo get_template_directory_uri(); ?>/bootstrap/css/bootstrap.css" /> 
<script>
    $=jQuery;
    $(document).ready(function(){
        //set css default 
        $("#main-pic").css("height","180px");
        $("#main-pic").css("background-color","#AAAAAA");
        
        
        $("#product_name").focus();
        //main image product.
          $("#main-pic").click(function(){
            $("#upload_img_product").click();
        });
        //ngăn đệ quy
        $("#upload_img_product").click(function(e){
            e.stopPropagation();
        });
        $("#upload_img_product").change(function(){
            var files = $("#upload_img_product")[0].files;
            //console.log(files);
            var formdata = new FormData($("#myform")[0]);
            var url = "<?php echo get_template_directory_uri(); ?>/controller/product-controller.php";
            $("#loading_image").show();
            if (formdata) {  
                $.ajax({  
                    url: url,  
                    type: "POST",  
                    data: formdata,  
                    processData: false,  
                    contentType: false,  
                    success: function (res) {  
                        showImageAfterUpload(res);
                        
                        //set css default 
                        $("#main-pic").css("height","auto");
                        $("#main-pic").css("background-color","#FFFFFF");
                    }  
                });  
            }  
        }); 
        
    });
    function showImageAfterUpload(res)
        {
            $("#loading_image").hide();
            res = jQuery.parseJSON(res);
            $("#product_image").val(res.img);
            $("#product_attachment_id").val(res.attachment_list);
            var imageList = res.img;
            var arrImage = imageList.split(",");
            for(i=0; i<arrImage.length;i++ ){
                if(i==0){
                    $("#img_main_pic").attr("src", arrImage[0]);
                }else {
                    $("#img_thumb_" + i).attr("src", arrImage[i]);

                }
            }
        }
        
    function setEventRemoveTags(){
        $(".ntdelbutton").each(function(){
            $(this).click(function(){
                var element =  $(this).parent();
                element.hide(500, function(){
                    element.remove();
                });
            });
    });
}

    function addElement(value){
        var content = "<span class='spanchecktags'><a class='ntdelbutton'>X</a><span class='valueTag'>" + value + "</span></span>";
        $("#listTags").append(content);
        setEventRemoveTags();
    }
</script>

<style>
    .insert-product-input{
        float:right;
    }
    .table{background:None;}
    .table ul{float:left;margin:0px;padding:0px;}
    .table ul li{list-style:none;padding:5px 9px;}
    .table ul li.title{font-weight:bold;background:#333;color:#fff;}
    .table ul li.even{background:#fff;}
    .table ul li.odd{background:#fff;}

    .btn_submit{
        width: 111px;
        height: 30px;

    }
    #loading_image{
        position: absolute;
        margin-left: 69px;
        margin-top: 30px;
        display: none;
    }
    #thumbs-pic{
        padding-left: 14px !important;
    }
    .notify{
        margin: 0px 0 5px;
        background-color: #ffffe0;
        border-color: #e6db55;
        border-radius: 3px;
        border-width: 1px;
        border-style: solid
    }
     .notify p{
        padding-left: 1em;
        padding-top: 0.5em;
        
    }
    .tagchecklist span a {
        margin: 5px 0 0 -9px;
        cursor: pointer;
        width: 10px;
        height: 10px;
        display: block;
        float: left;
        text-indent: -9999px;
        overflow: hidden;
        position: absolute;
        background: url(<?php echo get_admin_url(); ?>images/xit.gif) no-repeat -10px 0;
    }
    .tagchecklist {
        font-size: 12px;
        overflow: auto;
    }
    
    #itags{
        width: 550px;
        height: 27px;
        font-size: 16px;

    }

    .tagchecklist span {
        cursor: default;
        display: block;
        float: left;
        font-size: 11px;
        line-height: 1.8em;
        margin-right: 25px;
        white-space: nowrap;
    }
    .spanchecktags{
        position: relative;
        margin: 10px;
    }
</style>



<?php

if (sizeof($_POST) > 0) {
    global $current_user;
    get_currentuserinfo();
    require_once( get_template_directory() . '/includes/forms/step-functions.php' );
    require_once( get_template_directory() . '/model/product-model.php' );

    $advals = array();
    $advals['name'] = appthemes_filter($_POST['post_title']);
    $advals['description'] = $_POST["my_editor"];
    $advals['user_id'] = $current_user->ID;
    $advals['category_id'] = $_POST["cat"];
    $advals['price'] = ( empty($_POST['cp_price']) ) ? '' : appthemes_clean_price($_POST['cp_price']);
    $advals['code'] = empty($_POST['product_code']) ? '' : $_POST['product_code'];
    $advals['source'] = empty($_POST['product_source']) ? '' : $_POST['product_source'];
    $advals['amount'] = empty($_POST['product_amount']) ? '' : $_POST['product_amount'];
    $advals['status'] = empty($_POST['product_status']) ? '' : $_POST['product_status'];
    $advals['time_created'] = time();
	
    $imageList = $_POST['product_image'];
    $imageProduct = empty($imageList) ? '' : $imageList;
    $advals['options'] = empty($_POST['product_image']) ? '' : $_POST['product_image'];
	$pid = ProductModel::insertNewProduct($advals);
	$attachmentIdList = $_POST['product_attachment_id'];
    if ($pid !=false) {
        add_post_meta($pid, 'product_attachment_image' , $attachmentIdList);
        
    }
}

$product_update_id = 0;
if(isset($_REQUEST["product_id"]) && $_REQUEST["product_id"]!=""){
     $product_update_id = $_REQUEST["product_id"]; 
     $product_data_array = ProductModel::selectProduct("SELECT * FROM ys_product where id =".$product_update_id,
             OBJECT); 
     if($product_data_array == null){
        $product_update_id = 0;
    }
    else
    {
        $product_data = $product_data_array[0];
        get_currentuserinfo();
        if($product_data->user_id != $current_user->ID)
        {
            wp_redirect(home_url());
        }
        $arr_url;
        $list_attachment_id = array();
        $stringIdPostAttachment = get_post_meta($product_update_id, "product_attachment_image", True);
        $listIdPostAttachment = split(",", $stringIdPostAttachment);
        $imgSize = 'large';
        for( $i=0;$i<sizeof($listIdPostAttachment);$i++)
        {
            $attach_id = $listIdPostAttachment[$i];
            $srcArr = wp_get_attachment_image_src($attach_id,$imgSize);
            $src = $srcArr[0];
            $arr_url = $arr_url.$src.",";
            array_push($list_attachment_id, $attach_id);
            $imgSize = 'thumbnail';
        }
        $arr_url = substr($arr_url, 0, strlen($arr_url) - 1);
        $result = array(
            "img" => $arr_url,
            "attachment_list"=> $list_attachment_id);
//        echo ;
        echo "<script>
            $(document).ready(function(){
                var prepareImgData = '".json_encode($result)."';
                showImageAfterUpload(prepareImgData);
            });
     </script>";
        
        
        echo "<script> 
            $(document).ready(function(){
            var prepareImgData = '".$product_data->options."';
                if(prepareImgData!='')
                {
                    var tagsData = jQuery.parseJSON(prepareImgData);
                    for(i=0; i<tagsData.tags.length;i++ ){
                        var value = tagsData.tags[i];
                        addElement(value);
                    };
                }
            });
     </script>";
    }
}

?>

<div class="content">
    <div class="content_botbg">
        <div class="content_res" id="content_res">
            <span id="notify_result"></span>
            <form action="<?php echo get_template_directory_uri()."/controller/product-controller.php"; ?>" name="myform" id="myform" method="POST" enctype="multipart/form-data">
                <input type="hidden" id="product_image" name ="product_image"/>
                <input type="hidden" id="product_attachment_id" name ="product_attachment_id"/>
                <div class="content_left">
                    <div class="shadowblock_out ">
                        <div class="shadowblock">
                            <h1 class="single-listing">
                                <a href="javascript:void(0)" title="Tên sản phẩm ở đây">
                                    <input type="text" id="product_name" value="<?php 
                                        if($product_update_id!=0){
                                            echo $product_data->name;
                                        }
                                        ?>" placeholder="Tên sản phẩm ở đây" style="width:330px; float: left;" name="post_title"/>
                                </a>
                            </h1>

                            <div class="price-wrap">
                                <span class="tag-head"></span>
                                <p class="post-price">
                                    <input type="text" id="product_price" value="<?php     
                                        if($product_update_id!=0){
                                            echo $product_data->price;
                                        }
                                    ?>" placeholder="Giá sản phẩm"/>
                                </p>
                            </div>
                            
                            
                            <div class="clr"></div>
                            <div class="pad5 dotted"></div>

                            <div class="bigright table">
                                <ul>
                                    <li class="titile"><span>Mã số:</span></li>
                                    <li class="odd"><span>Xuất xứ:</span></li>
                                    <li class="odd"><span>Số lượng:</span></li>
                                    <li class="odd"><span>Tình trạng:</span></li>
                                    <li class="odd"><span>Danh mục:</span></li>

                                </ul>
                                <ul>
                                    <li class="">
                                        <input type="text" class="insert-product-input" id="product_code" name="product_code" placeholder="Mã số sản phẩm" value="<?php     
                                        if($product_update_id!=0){
                                                    echo $product_data->code;
                                                }
                                            ?>"/>
                                    </li>
                                    <li class="">
                                        <input type="text" class="insert-product-input" id="product_source" name="product_source" value="<?php     
                                            if($product_update_id!=0){
                                                    echo $product_data->source;
                                                }
                                            ?>" placeholder="Xuất xứ sản phẩm"/>
                                    </li>
                                    <li class="">
                                        <input type="text" class="insert-product-input" id="product_amount" name="product_amount" value="<?php     
                                            if($product_update_id!=0){
                                                    echo $product_data->amount;
                                                }
                                            ?>" placeholder="Số lượng sản phẩm"/>
                                    </li>
                                    <li class="">
                                        <select id="product_status" name="product_status">
                                            <option value="new" <?php if($product_update_id!=0 & $product_data->status == "new") {echo "selected";} ?> >Mới</option>
                                            <option value="old" <?php if($product_update_id!=0 & $product_data->status == "old") {echo "selected";} ?> >Cũ</option>
                                        </select>
                                    </li>
                                    <li class="" name="category" id="product_category">
                                         <?php
                                            $selectedCateId = 0;
                                            if($product_update_id!=0){
                                                $selectedCateId = $product_data->category_id;
                                            }
                                            //dùng hàm có sẵn của wp để lấy danh mục, cái này chúng ta không custom
                                            wp_dropdown_categories('show_option_none=&class=dropdownlist&orderby=name&order=ASC&hide_empty=0&hierarchical=1&taxonomy=category&depth=1&selected='.$selectedCateId);
                                        ?>
                                    </li>

                                </ul>
                                
                            </div><!-- /bigright -->
                            <div class="bigleft">
                                <span id="loading_image">
                                    <img src="<?php echo get_template_directory_uri() . "/images/loading.gif" ?>" width="100" height="100" style="opacity: 1;">
                                </span>
                                <div id="main-pic">
                                    <a href="javascript:void(0)" class="img-main cboxElement" data-rel="colorbox" style="opacity: 1;">
                                        <img style="width:200px; height: 132px;" id="img_main_pic" src="" title="Click để up hình của sản phẩm." alt="Hình đại diện cho sản phẩm"></a>
                                    <input type="file" id="upload_img_product" name="app_attachment_file[]" multiple style="display:none;">
                                    <div class="clr"></div>
                                </div>
                                <div id="thumbs-pic">
                                    <a href="javascript:void(0);" class="thumbs" data-rel="colorbox" title="Acoustic Guitar - Image 1">
                                        <img id="img_thumb_1" src="" alt="" title="" width="50" height="50" style="opacity: 1;">
                                    </a>
                                    <a href="javascript:void(0);" class="thumbs" data-rel="colorbox" title="Acoustic Guitar - Image 1">
                                        <img src="" id="img_thumb_2" alt="" title="" width="50" height="50" style="opacity: 1;">
                                    </a>
                                    <a href="javascript:void(0);" class="thumbs" data-rel="colorbox" title="Acoustic Guitar - Image 1">
                                        <img src="" id="img_thumb_3" alt="" title="" width="50" height="50" style="opacity: 1;">
                                    </a>
                                    <a href="javascript:void(0);" class="thumbs" data-rel="colorbox" title="Acoustic Guitar - Image 1">
                                        <img src="" id="img_thumb_4" alt="" title="" width="50" height="50" style="opacity: 1;">

                                    </a>

                                    <div class="clr"></div>
                                </div>

                            </div><!-- /bigleft -->
                            <div class="clr"></div>
                            <div class="single-main">
                                <h3 class="description-area">Mô tả sản phẩm</h3>
                                <p><?php 
                                $desContent = "";
                                if($product_update_id!=0){
                                    $desContent = $product_data->description;
                                }
                                wp_editor($desContent, "my_editor", array('media_buttons' => true, "editor_height" => "450")); ?>
                                </p>

                            </div>
                            <div id="tagsdiv-post_tag" class="postbox">
                                <div class="inside">
                                    <div class="tagsdiv" id="post_tag">
                                        <div class="jaxtag">
                                            <input type="hidden" name="post_tags" class="the-tags" id="iTagsList" value="" />
                                            <div class="ajaxtag">
                                                <input type="text" name="newtag[post_tag]" class="newtag form-input-tip" size="16" autocomplete="off" value="" id="itags" placeholder="Nhập tag cho bài viết, nhấn enter để thêm tag."/>
                                            </div>
                                        </div>
                                        <div class="tagchecklist" id="listTags">
                                            <?php
                                            if($post_update_id!=0){
                                                $tags =  $post_data->tags_input ;
                                                foreach ($tags as $key => $value) {
                                                 echo '<span class="spanchecktags"><a class="ntdelbutton">X</a><span class="valueTag">'.$value.'</span></span>';
                                             }   
                                            } 
                                            ?>
                                        </div>
                                    </div>
                                    <!--                        <p class="tagcloud-link">Hoáº·c <a href="javascript: void(0);" class="tagcloud-link" id="link-post_tag">Chá»�n cÃ¡c tháº» cÃ³ sáºµn</a></p>-->
                                </div>
                            </div>
                        </div><!-- /shadowblock -->

                    </div><!-- /shadowblock_out -->
                    <div class="clr"></div>
                </div><!-- /content_left -->

                <!-- right sidebar -->
                <div class="content_right">
                    <div class="tabprice">
                        <div id="priceblock1" style="">

                            <div class="clr"></div>

                            <div class="singletab">
                                <input type="text" placeholder="Tên Thương Hiệu" style="width: 92%; margin: 10px; margin-bottom: 0px;" id="product_brand_name">
                                <input type="button" id="img_button_brand_upload" style="cursor:pointer; margin: 10px;" value="Up hình đại diện cho thương hiệu"/>
                                <input type="file" name="brand_image" id="input_button_brand_upload" style="display: none;" value="" ></input>
                                <textarea  placeholder="Mô tả về thương hiệu" rows="20" style="width: 92%; font-family: arial; margin: 10px;" id="product_brand_description"></textarea>
                            </div><!-- /singletab -->

                        </div>
                    </div><!-- /tabprice -->

                </div><!-- /content_right -->

                <div class="clr"></div>
                <!--button-->
                <div style="margin-left: auto; margin-right: auto; width: 590px;">
<!--                    <input type="button" value="Xem trước" class="btn_submit" id="btn_review">-->
                    <input type="button" value="Đăng sản phẩm" class="btn_submit" id="btn_submit">
                </div>
            </form            
        </div><!-- /content_res -->
    </div><!-- /content_botbg -->

</div>
<script type='text/javascript'>
    var $= jQuery;
    function get_tinymce_content(){
        return tinyMCE.activeEditor.getContent();
        
        if (jQuery("#my_editor").hasClass("tmce-active")){
            return tinyMCE.activeEditor.getContent();
        }else{
            return "";
        }
    }
    $(document).ready(function(){
        
        
        $("#my_editor_ifr").attr("height", "20px");


        $("#img_button_brand_upload").click(function(){
            $("#input_button_brand_upload").click();
        });
        $("#btn_review").click(function(){
            console.log("review");
        });
        $("#btn_submit").click(function(){
            //check title
            var title = $("#product_name").val();
            if(title.length <=0){
                $("#product_name").focus();
                $("#product_name").attr("placeholder", "Vui lòng nhập tên sản phẩm");
				$("#product_name").css('border-color', 'red');
				return false;
            }
            var amount = $("#product_amount").val();
            if(amount.length <=0){
                $("#product_amount").focus();
                $("#product_amount").attr("placeholder", "vui lòng nhập số");
                $("#product_amount").css('border-color', 'red');
                return false;
            }
            var tags = "";
            $(".valueTag").each(function(){
                tags += '"' + $.trim($(this).text()) + '",';
            });
            
            if(tags.length > 0)
            {
                tags = tags.substr(0,tags.length - 1);
                tags = '{"tags": ['+tags+']}';
            }
            
            //OK, pass 
            var pTitle = $("#product_name").val();
            var pPrice = $("#product_price").val();
            var pCode = $("#product_code").val();
            var pSource = $("#product_source").val();
            var pAmount = $("#product_amount").val();
            var pStatus = $("#product_status").val();
            var pCate = $("#cat").val();
            var pImage = $("#product_image").val();
            var pAttach = $("#product_attachment_id").val();
            var pDes = get_tinymce_content();;
            
                
            var formURL = $("#myform").attr("action");
            $.ajax(
            {
                    url : formURL,
                    type: "POST",
                    <?php
                        if($product_update_id == 0)
                        {
                            echo                        
                            'data : {action: "insert_new_product",title: pTitle, price: pPrice, code: pCode, source: pSource, 
                                amount: pAmount, status: pStatus, category: pCate, description: pDes, img: pImage, attachment: pAttach,
                                tags: tags
                            },';
                        }
                        else
                        {
                            echo                        
                            'data : {action: "insert_new_product", current_id: "'. $product_update_id .'", title: pTitle, price: pPrice, code: pCode, source: pSource, 
                                amount: pAmount, status: pStatus, category: pCate, description: pDes, img: pImage, attachment: pAttach,
                                tags: tags
                            },';
                        }
                    ?>
                    success:function(res)
                    {
                        res = jQuery.parseJSON(res);
                        
                        if(res.err == 0){
                            pid = res.pid;
                            var page_id = <?php echo get_id_by_filename("tpl-product-single.php"); ?>;
                            urlProductDetail = "<?php echo get_site_url(); ?>" + "?page_id=" +page_id +"&pid="+pid;
                           
                            var notify = "<div class=\"notify\"><p>Up sản phẩm thành công. Xem <a href=\""+urlProductDetail+"\">sản phẩm </a>vừa up. Hoặc vào trang quản lý chung</p></div>";
                            $("#notify_result").html(notify);
                            $('html,body').animate({ scrollTop: 0 }, 'fast');
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown)
                    {
                            alert("Có lỗi xảy ra, vui lòng thử lại");
                            //if fails     
                    }
            });
           
        });
        $( "#product_amount" ).keypress(function(e) {
                var charCode = e.which;
                if(charCode > 31 && (charCode < 48 || charCode > 57)){
                        e.preventDefault();
                        }
        });
        
        function checkDuplicatteListTags(value){
        var isDuplicate = false;
        $(".valueTag").each(function(){
            var valueCompare = $(this).text();
            if(valueCompare == value){
                        isDuplicate = true; //shit, co roi
                    }
                });
        return isDuplicate;
        }
        
         //set event remove tag in case edit post
         setEventRemoveTags();
         $( "#itags" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                 url: "<?php echo get_template_directory_uri() . "/controller/post-controller.php" ?>",
                    // url: "<?php echo get_template_directory_uri() . "/functions.php" ?>",
                    dataType: "json",
                    data: {
                        action: "suggestion_tag",
                        key: $( "#itags" ).val()
                    },
                    success: function( data ) {
                        response( $.map( data, function( item ) {
                            return {
                                label: item,
                                value: item
                            }
                        }));
                    }
                });
            },
            minLength: 1,
            select: function( event, ui ) {
                //add element
                var value = ui.item.value;
                var isDuplicate = checkDuplicatteListTags(value);
                if(!isDuplicate){
                    addElement(value);
                }                        
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );

            },
            open: function() {
                //                $("#itags").keydown(function(e){
                //                    if(e.keyCode == 13){
                //                        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
                //                    }
                //                });

},
close: function() {
    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}).keyup(function (e) {
    if(e.which === 13) {
        $(".ui-autocomplete").hide();
    }            
});

$("#itags").keydown(function(e){
    if(e.keyCode == 13){
        var value = $("#itags").val();
        if(value != null && value != "" ){
            var isDuplicate = checkDuplicatteListTags(value);
            if(!isDuplicate)
                addElement(value);
            $("#itags").val("");
            $("#itags").removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }
    }

});



    });
            
</script>